import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import calculator
import db

class App:
    def __init__(self):
        self.root = tk.Tk()
        #messagebox.showinfo("提示", "请不要关闭命令行窗口，否则程序将退出！", parent=self.root)
        self.root.title('评估费计算器')
        self.root.wm_attributes('-topmost', 1)
        
        self.notebook = ttk.Notebook(self.root)
        
        # 创建三个计算器标签页
        self.create_real_estate_tab()
        self.create_land_tab()
        self.create_asset_tab()
        
        self.notebook.pack(expand=1, fill='both')
        self.create_history_view()
        
    def create_real_estate_tab(self):
        frame = ttk.Frame(self.notebook)
        ttk.Label(frame, text='评估金额（万元）').grid(row=0, column=0, padx=10, pady=10)
        self.real_estate_entry = ttk.Entry(frame)
        self.real_estate_entry.grid(row=0, column=1, padx=10, pady=10)
        
        self.result_label_real = tk.Label(frame, text='评估费：0.0000 万元', foreground='#FA812F')
        self.result_label_real.grid(row=1, column=0, columnspan=2)
        
        ttk.Label(frame, text='折扣率').grid(row=2, column=0, padx=10, pady=10)
        self.discount_entry_real = ttk.Entry(frame)
        self.discount_entry_real.grid(row=2, column=1, padx=10, pady=10)
        
        self.discounted_result_label_real = tk.Label(frame, text='折后价：0.0000 万元', foreground='#FA812F')
        self.discounted_result_label_real.grid(row=3, column=0, columnspan=2)
        self.real_estate_entry.bind('<KeyRelease>', lambda e: self.calculate('房产', self.real_estate_entry, self.discount_entry_real))
        self.discount_entry_real.bind('<KeyRelease>', lambda e: self.calculate('房产', self.real_estate_entry, self.discount_entry_real))
        self.notebook.add(frame, text='房产评估')

    def create_land_tab(self):
        frame = ttk.Frame(self.notebook)
        ttk.Label(frame, text='评估金额（万元）').grid(row=0, column=0, padx=10, pady=10)
        self.land_entry = ttk.Entry(frame)
        self.land_entry.grid(row=0, column=1, padx=10, pady=10)
        
        self.result_label_land = tk.Label(frame, text='评估费：0.0000 万元', foreground='#183B4E')
        self.result_label_land.grid(row=1, column=0, columnspan=2)
        
        ttk.Label(frame, text='折扣率').grid(row=2, column=0, padx=10, pady=10)
        self.discount_entry_land = ttk.Entry(frame)
        self.discount_entry_land.grid(row=2, column=1, padx=10, pady=10)
        
        self.discounted_result_label_land = tk.Label(frame, text='折后价：0.0000 万元', foreground='#183B4E')
        self.discounted_result_label_land.grid(row=3, column=0, columnspan=2)
        self.land_entry.bind('<KeyRelease>', lambda e: self.calculate('土地', self.land_entry, self.discount_entry_land))
        self.discount_entry_land.bind('<KeyRelease>', lambda e: self.calculate('土地', self.land_entry, self.discount_entry_land))
        self.notebook.add(frame, text='土地评估')

    def create_asset_tab(self):
        frame = ttk.Frame(self.notebook)
        ttk.Label(frame, text='评估金额（万元）').grid(row=0, column=0, padx=10, pady=10)
        self.asset_entry = ttk.Entry(frame)
        self.asset_entry.grid(row=0, column=1, padx=10, pady=10)
        
        self.result_label_asset = tk.Label(frame, text='评估费：0.0000 万元', foreground='#183B4E')
        self.result_label_asset.grid(row=1, column=0, columnspan=2)
        
        ttk.Label(frame, text='折扣率').grid(row=2, column=0, padx=10, pady=10)
        self.discount_entry_asset = ttk.Entry(frame)
        self.discount_entry_asset.grid(row=2, column=1, padx=10, pady=10)
        
        self.discounted_result_label_asset = tk.Label(frame, text='折后价：0.0000 万元', foreground='#183B4E')
        self.discounted_result_label_asset.grid(row=3, column=0, columnspan=2)
        self.asset_entry.bind('<KeyRelease>', lambda e: self.calculate('资产', self.asset_entry, self.discount_entry_asset))
        self.discount_entry_asset.bind('<KeyRelease>', lambda e: self.calculate('资产', self.asset_entry, self.discount_entry_asset))
        self.notebook.add(frame, text='资产评估')

    def calculate(self, calc_type, entry_widget, discount_widget):
        try:
            amount = float(entry_widget.get())
            result = round(calculator.FeeCalculator.calculate(amount, calc_type), 4)
            discount = discount_widget.get()
            original_result = result
            if discount:
                try:
                    discount_rate = float(discount)
                    result = round(result * discount_rate, 4)
                except ValueError:
                    pass
            
            if calc_type == '房产':
                self.result_label_real.config(text=f'评估费：{original_result:.4f} 万元')
                self.discounted_result_label_real.config(text=f'折后评估费：{result:.4f} 万元')
            elif calc_type == '土地':
                self.result_label_land.config(text=f'评估费：{original_result:.4f} 万元')
                self.discounted_result_label_land.config(text=f'折后评估费：{result:.4f} 万元')
            else:
                self.result_label_asset.config(text=f'评估费：{original_result:.4f} 万元')
                self.discounted_result_label_asset.config(text=f'折后评估费：{result:.4f} 万元')
            db.Database().add_record(calc_type, amount, original_result, discount if discount else '无', result)
            self.load_history()
        except ValueError:
            pass

    def create_history_view(self):
        history_frame = ttk.Frame(self.root)
        history_frame.pack(fill='both', expand=True)
        
        columns = ('类型', '金额', '评估费', '折扣率', '折后评估费', '时间')
        self.tree = ttk.Treeview(history_frame, columns=columns, show='headings')
        for col in columns:
            self.tree.heading(col, text=col)
            self.tree.column(col, width=150 if col == '时间' else 80, stretch=True)
        
        scrollbar = ttk.Scrollbar(history_frame, orient='horizontal', command=self.tree.xview)
        scrollbar.pack(side='bottom', fill='x')
        self.tree.configure(xscrollcommand=scrollbar.set)
        self.tree.pack(fill='both', expand=True)
        
        # 添加删除按钮
        btn_frame = ttk.Frame(history_frame)
        btn_frame.pack(pady=5)
        
        self.clear_btn = ttk.Button(btn_frame, text='清空历史记录', 
                                  command=lambda: [db.Database().delete_all_records(), self.load_history()])
        self.clear_btn.pack(side='right', padx=10)
        
        self.load_history()

    def load_history(self):
        for item in self.tree.get_children():
            self.tree.delete(item)
        for record in db.Database().get_history():
            formatted_record = (
                record[0],
                f'{record[1]:.4f}',
                f'{record[2]:.4f}',
                record[3],
                f'{record[4]:.4f}',
                record[5]
            )
            self.tree.insert('', 'end', values=record)

if __name__ == '__main__':
    app = App()
    app.root.mainloop()